<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { XtxGuessInstance } from '@/types/component'
import { getbannerHomeAPI, getHomeCategoryMutli, getHomeHotMutli } from '@/apis/home'
import type { BannerHomeItem, HomeCategoryItem, HotPanelItem } from '@/types/home'
import XtxGuess from '@/components/XtxGuess/XtxGuess.vue'
import CustomNavbar from '@/components/CustomNavbar/CustomNavbar.vue'
import CategoryPanel from '@/components/CategoryPanel/CategoryPanel.vue'
import HotPanel from '@/components/HotPanel/HotPanel.vue'
import XtxSwiper from '@/components/XtxSwiper/XtxSwiper.vue'
import { useGuessList } from '@/composables'

// 获取安全区
const { safeArea } = uni.getWindowInfo()

// 获取轮播图列表
const bannerList = ref<BannerHomeItem[]>([])
const getBannerList = async () => {
  const res = await getbannerHomeAPI(1)
  // console.log(res.result)
  bannerList.value = res.result
}
onLoad(() => {
  getBannerList()
})

// 获取前台分类
const categoryList = ref<HomeCategoryItem[]>([])
const getCategoryList = async () => {
  const res = await getHomeCategoryMutli()
  // console.log(res)
  categoryList.value = res.result
}
onLoad(() => {
  getCategoryList()
})

// 获取热门推荐
const hotPanelList = ref<HotPanelItem[]>([])
const getHotPanelList = async () => {
  const res = await getHomeHotMutli()
  // console.log(res)
  hotPanelList.value = res.result
}
onLoad(() => {
  getHotPanelList()
})

// // 获取猜你喜欢组件实例
// const GuessRef = ref<XtxGuessInstance>()

// // 滚动触底事件
// const onScrolltoLower = () => {
//   console.log('触底')
//   GuessRef.value?.getMore()
// }

// 获取猜你喜欢组件实例
const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置数据
  guessRef.value?.resetData() //加载数据
  await Promise.all([
    getBannerList(),
    getCategoryList(),
    getHotPanelList(),
    guessRef.value?.getMore(),
  ])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <view class="index" :style="{ paddingTop: safeArea.top + 'px' }">
    <!-- 自定义导航栏 -->
    <CustomNavbar />
    <!-- 猜你喜欢 -->
    <scroll-view
      scroll-y
      @scrolltolower="onScrolltolower"
      refresher-enabled
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered"
      class="scroll-view"
    >
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 前台分类 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotPanelList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="GuessRef" />
    </scroll-view>
  </view>
</template>

<style lang="scss">
Page {
  display: flex;
  height: 100%;
  flex-direction: column;
  background-color: #d8d8d8;
}
.scroll-view {
  flex: 1;
}
</style>
